#!/usr/bin/env python

import numpy as np
import pylab as pl
import os.path as osp
import sys
from matplotlib.font_manager import FontProperties as FP


def new_frame(filep):
	line = '1'
	while not line.startswith('[/FRAME]'):
		line = filep.readline()
		if line.startswith('pkt_pos='):
			pos = int(line[line.find('=')+1:])
		if line.startswith('pict_type='):
			pict_type = line[line.find('=')+1:-1]
	return pos, pict_type


if __name__ == '__main__':
	input_filename = sys.argv[1]

	f = open(input_filename,'r')

	histogram_bin_size = 100

	pos_type = []


	##### DATA EXTRACTION #####

	line = '1'
	while line:
		line = f.readline()
		if line.startswith('[FRAME]'):
			position, pict_type = new_frame(f)
			pos_type.append((position, pict_type))

	frame_sizes = []

	max_size = 0
	min_size = 1000000

	p_size_array = []
	i_size_array = []

	for i in range(len(pos_type)-1):
		size = pos_type[i+1][0] - pos_type[i][0]
		size = size/1024. ### FILESIZE IN KILOBYTES!!
		if size < min_size:
			min_size = size
		if size > max_size:
			max_size = size
		frame_sizes.append(size)
		if str(pos_type[i][1]).lower() == 'p':
			p_size_array.append(size)
		else:
			i_size_array.append(size)

	##### PLOTTINGS #######



	hist_i = pl.histogram(i_size_array, histogram_bin_size, (min_size, max_size))
	hist_p = pl.histogram(p_size_array, histogram_bin_size, (min_size, max_size))

	hist = pl.histogram(frame_sizes,histogram_bin_size, (min_size, max_size))

	fp = FP()
	fp.set_size('small')


	fig = pl.figure()
	ax1 = fig.add_subplot(111)
	bar_p = ax1.bar(hist_p[1][:-1],hist_p[0], width=(max_size-min_size)/histogram_bin_size, color='blue', alpha=0.6, label='P-frames')
	ax1.tick_params(axis='y', colors='blue')
	ax1.set_ylabel('P-frame count [-]', color='blue')

	ax2 = ax1.twinx() # Create another y axis
	bar_i = ax2.bar(hist_i[1][:-1],hist_i[0], width=(max_size-min_size)/histogram_bin_size, color='red', alpha=0.5, label='I-frames')
	ax2.tick_params(axis='y', colors='red')
	ax2.set_ylabel('I-frame count [-]', color='red')

	ax1.set_xlabel('Frame size [kB]')

	### SETTING NOTATIONS ###

	psize = np.sum(p_size_array)
	isize = np.sum(i_size_array)
	totalsize = isize+psize

	print isize, psize
	print 'I-frame data percentage', (isize/totalsize)*100
	print 'I-frame average size', isize/len(i_size_array)
	print 'P-frame data percentage', (psize/totalsize)*100
	print 'P-frame average size', psize/len(p_size_array)

	p_size_mb = psize/1024.
	p_size_mb_str = str("%.1f" % p_size_mb)
	i_size_mb = isize/1024.
	i_size_mb_str = str("%.1f" % i_size_mb)


	p_label = 'P-frames ('+str(len(p_size_array))+' frames, '+p_size_mb_str+' MB)'
	print p_label
	i_label = 'I-frames ('+str(len(i_size_array))+' frames, '+i_size_mb_str+' MB)'
	print i_label

	pl.legend((bar_p[0], bar_i[0]), (p_label, i_label), prop=fp) 

	output_filename = input_filename.split('.')
	output_filename = output_filename[0]


	svndir = osp.abspath('../../rapport/figs')

	pl.savefig(svndir+'/'+output_filename+'.png')

	









